package com.gg.aliyun.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.gg.aliyun.oss.service.OSSApiService;
import com.gg.aliyun.oss.utils.ConstantOSSPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * Author：  chenjunjia
 * Date：    2022/4/21 10:01
 * WeChat：  China_JoJo_
 */
@Service
public class OSSApiApiServiceImpl implements OSSApiService {

    String endpoint = "oss-cn-shenzhen.aliyuncs.com";

    String accessKeyId = "LTAI5tMwgQNSXsNp3Tn6bZaf";

    String accessKeySecret = "FGuNs3guTtlWqZDP13LlxhCEGzhfMu";

    String bucketName = "registration-hospital01";

    @Override
    public String fileUpload(MultipartFile multipartFile) throws IOException {
        //创建OSS实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        //上传文件流
        InputStream inputStream = multipartFile.getInputStream();
        //文件名
        String fileName = multipartFile.getOriginalFilename();
        //生成随机值，使用UUID，添加到文件名称后面
        //若不添加随机值，文件重名的话会导致文件覆盖，比如都叫 aaa.jpg
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        //按照当前日期创建文件夹，上传到创建的文件夹里
        String timeUrl = new DateTime().toString("yyyy/MM/dd");
        fileName = timeUrl + "/" + uuid + fileName;
        //调用方法实现上传
        ossClient.putObject(bucketName,fileName,inputStream);
        //关闭OSSClient
        ossClient.shutdown();
        //上传之后拼接文件路径后返回
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

        return url;
    }
}


















